package com.idanchuang.component.businesslog.es.util;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author jiang
 * @date 2019-11-25 19:12
 */
public class DocumentUtil {

    /**
     * 对象装换
     *
     * @param entity 入参
     * @return content
     */
    public static XContentBuilder toField(Object entity) {
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder();
            builder.startObject();

            Field[] fields = entity.getClass().getDeclaredFields();
            Arrays.stream(fields).forEach(field -> {
                field.setAccessible(true);
                try {
                    builder.field(field.getName(), field.get(entity));
                } catch (IOException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            });

            builder.endObject();
            return builder;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
